package com.employee.service.impl;

import com.employee.exception.EmailSendFalseException;
import com.employee.mapper.UserMapper;
import com.employee.pojo.dto.UserDTO;
import com.employee.pojo.entry.User;
import com.employee.service.EmailService;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private UserMapper userMapper;
    @Override
    public String sendVerificationEmail(String email, String captcha) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("1597310496@qq.com");
        message.setTo(email);
        message.setSubject("验证码邮件");
        message.setText("您的验证码是：" + captcha + "，请在10分钟内完成验证。");
        try {

            // 处理邮件发送成功逻辑
            User byEmail = userMapper.selectByEmail(new UserDTO(email, null));
            if (byEmail != null) {
                javaMailSender.send(message);
                System.out.println("验证码邮件发送成功");
                User user = new User();
                user.setEmpId(byEmail.getEmpId());
                user.setPassword(BCrypt.hashpw(captcha, BCrypt.gensalt()));
                user.setUpdateTime(LocalDateTime.now());
                userMapper.update(user);
                return "密码修改成功";
            }
            throw new EmailSendFalseException("邮箱未注册");
        } catch (Exception e) {
            throw new EmailSendFalseException("邮箱发送失败");
        }
    }
}
